﻿using System;
using System.Data;

namespace Nardax.Data
{
    /// <summary> 
    /// A couple of generic extensions to making getting data out of an IDataReader as easy as possible.
    /// </summary> 
    public static class IDataReaderExtensions
    {
        public static T GetValue<T>(this IDataReader reader, string columnName)
        {
            if (typeof(T).IsEnum)
            {
                return (T)Enum.Parse(typeof(T), reader.GetValue<String>(columnName));
            }

            return (T)Convert.ChangeType(reader[columnName], typeof(T));
        }

        public static T? GetNullableValue<T>(this IDataReader reader, string columnName) where T : struct
        {
            if (reader[columnName] == DBNull.Value)
            {
                return new T?();
            }

            if (typeof(T).IsEnum)
            {
                return (T)Enum.Parse(typeof(T), reader.GetValue<String>(columnName));
            }

            return (T?)Convert.ChangeType(reader[columnName], typeof(T));
        }
    }
}